<template>
  <draggable
    :class="[containerClass ? containerClass: 'widget-form-list']"
    :list="localData.column"
    item-key="uuid"
    :group="{ name: 'form', put: true }"
    :ghost-class="curDragField && curDragField.span == 12 ? 'ghost' : 'ghostLine'"
    :animation="300"
    @add="handleWidgetAdd"
    @end="$emit('change')"
  >
    <template #item="{ element, index }">
      <div
        class="widget-form-table"
        v-if="
          element.type == 'dynamic' ||
            element.type == 'anvilDynamic' ||
            element.type == 'anvilTable'
        "
        :key="index"
        :class="{ active: isShowButton(element) }"
        @click.stop="handleSelectWidget(index)"
      >
        <widget-form-table
          v-model:data="localData"
          :column="element"
          :index="index"
          v-model:select="selectWidget"
          :attrList="attrList"
          @change="$emit('change')"
        />
      </div>
      <div
        class="widget-form-grid"
        v-else-if="
          element.type == 'anvilVforTable'
        "
        :key="`${element.type}_${index}`"
        :class="{ active: isShowButton(element) }"
        @click.stop="handleSelectWidget(index)"
      >
        <div class="widget-form-grid__item">
          <widget-form-container
            v-model:data="localData.column[index].children"
            v-model:select="selectWidget"
            :attrList="attrList"
          />
        </div>
        <widget-form-operation v-if="isShowButton(element)" @delete="handleWidgetDelete(index)" @clone="handleWidgetClone(index)" />
      </div>
      <div
        class="widget-form-group"
        v-else-if="element.type == 'group'"
        :key="`${element.uuid}_${index}`"
        :class="{ active: isShowButton(element) }"
        @click.stop="handleSelectWidget(index)"
      >
        <div>
          <h4 class="widget-form-group__head" v-show="localData.column[index].label">
            <i :class="localData.column[index].icon" v-show="localData.column[index].icon" style="margin-right: 10px" />
            {{ localData.column[index].label }}
          </h4>
          <div class="widget-form-group__body">
            <widget-form-container
              v-model:data="localData.column[index].children"
              v-model:select="selectWidget"
              :attrList="attrList"
            />
          </div>
          <widget-form-operation v-if="isShowButton(element)" :clear="true" @delete="handleWidgetDelete(index)" @clear="handleWidgetClear(index)" @clone="handleWidgetClone(index)" />
        </div>
      </div>
      <div
        v-else-if="element.type == 'template'"
        class="widget-form-table"
        :class="{ active: isShowButton(element) }"
        @click.stop="handleSelectWidget(index)"
      >
        <widget-form-template v-model:column="localData.column[index]" />
        <widget-form-operation v-if="isShowButton(element)" @delete="handleWidgetDelete(index)" @clone="handleWidgetClone(index)" />
      </div>
      <div
        class="widget-form-grid"
        v-else-if="element.type == 'grid'"
        :class="{ active: isShowButton(element) }"
        @click.stop="handleSelectWidget(index)"
      >
        <h4 class="widget-form-grid__head" v-show="element.label">{{ element.label }}</h4>
        <div class="widget-form-grid__body">
          <el-col v-for="(col, idx) in element.rows" :key="idx" :span="col.span">
            <div class="widget-form-grid__item">
              <widget-form-container
                v-model:data="localData.column[index].rows[idx]"
                v-model:select="selectWidget"
                :attrList="attrList"
              />
            </div>
          </el-col>
        </div>
        <widget-form-operation v-if="isShowButton(element)" @delete="handleWidgetDelete(index)" @clone="handleWidgetClone(index)" />
      </div>
      <div
        class="widget-form-tabs"
        v-else-if="element.type == 'anvilTabs'"
        :class="{ active: isShowButton(element) }"
        @click.stop="handleSelectWidget(index)"
      >
        <h4 class="widget-form-tabs__head" v-show="element.label">{{ element.label }}</h4>
        <div class="widget-form-tabs__body">
          <el-tabs :type="element.styleType" :tab-position="element.tabPosition">
            <el-tab-pane v-for="(tab, idx) in element.tabs" :key="idx" :label="tab.label" :name="tab.name">
              <div class="widget-form-tabs__item">
                <widget-form-container
                  v-model:data="localData.column[index].tabs[idx]"
                  v-model:select="selectWidget"
                  :attrList="attrList"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <widget-form-operation v-if="isShowButton(element)" @delete="handleWidgetDelete(index)" @clone="handleWidgetClone(index)" />
      </div>
      <el-col
        v-else
        :md="element.span || 12"
        :xs="24"
        :offset="element.offset || 0"
        :key="element.uuid"
        :style="{'margin-right' : element.row ? (24 - (element.span || 12)) / 24 * 100 + '%' : 'unset'}"
      >
        <el-form-item
          class="widget-form-item"
          v-if="element.isSystem == 'N' || element.isSystem == undefined"
          :label="element.label"
          :labelWidth="element.labelWidth !== undefined && element.labelWidth + 'px'"
          :prop="element.prop"
          :required="element.isRequired == 'Y'"
          :class="[
            {
              active: isShowButton(element)
            },
            'avue-form__item--' + element.labelPosition || ''
          ]"
          @click="
            (e) => {
              handleSelectWidget(index, e)
            }
          "
        >
          <widget-form-item
            :item="element"
            :params="element.params"
          />
          <widget-form-operation v-if="isShowButton(element)" @delete="handleWidgetDelete(index)" @clone="handleWidgetClone(index)" />
        </el-form-item>
      </el-col>
    </template>
  </draggable>
</template>

<script>
import WidgetFormItem from './WidgetFormItem.vue'
import WidgetFormTable from './WidgetFormTable.vue'
import WidgetFormTemplate from './WidgetFormTemplate.vue'
import widgetFormOperation from './widgetFormOperation.vue'
import Draggable from 'vuedraggable'
import { randomString } from '@/utils/zmids'
import { useCodeStore } from '@code/store'
import { generateValidUuid } from '@code/components/anvil-code-low-common/utils/common-methods'

export default {
  name: 'WidgetFormContainer',
  components: { Draggable, WidgetFormItem, WidgetFormTable, WidgetFormTemplate, widgetFormOperation },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    select: {
      type: Object,
      default: () => {}
    },
    showMobile: {
      type: Boolean,
      default: false
    },
    attrList: {
      type: Array,
      default: () => []
    },
    containerClass: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      selectWidget: this.select,
      form: {},
      localData: {}
    }
  },
  computed: {
    curDragField(){
      const { getCurDragField } = useCodeStore()
      return getCurDragField
    }
  },
  watch: {
    select: {
      handler(val){
        this.selectWidget = val
      },
      immediate:true
    },
    selectWidget: {
      handler(val) {
        this.$emit('update:select', val)
      },
      deep: true
    },
    data: {
      handler(newVal) {
        if (newVal) {
          this.localData = newVal
        }
      },
      deep: true,
      immediate: true
    },
    localData: {
      handler(newVal) {
        this.$emit('update:data', newVal)
      },
      deep: true
    }
  },
  methods: {
    handleSelectWidget(index, e) {
      if (e) {
        e.stopPropagation()
      }
      this.selectWidget = this.localData.column[index]
      console.log(this.selectWidget)
    },
    handleWidgetAdd(evt) {
      const newIndex = evt.newIndex
      const data = this.deepClone(this.localData.column[newIndex])

      // 父组件标识删除
      if (data.parentName) {
        delete data.parentName
      }

      // 复合组件的添加逻辑
      if (data.type == 'composite') {
        try {
          const { content } = data
          const contentObj = JSON.parse(content)
          const { column } = contentObj
          // 将复合组件内部的组件列表添加
          this.localData.column.splice(newIndex, 0, ...column)
          // 把复合组件的本身删除
          this.localData.column.splice(newIndex + column.length, 1)
        } catch (e) {
          console.log('error!', e)
        }
      }
      // 普通组件的添加逻辑
      else {
        this.localData.column.splice(newIndex, 1, data)
      }

      this.handleSelectWidget(newIndex)
      this.$emit('change')
    },
    handleWidgetDelete(index) {
      if (this.localData.column.length - 1 === index) {
        if (index === 0) this.selectWidget = {}
        else this.handleSelectWidget(index - 1)
      } else this.handleSelectWidget(index + 1)

      this.$nextTick(() => {
        this.localData.column.splice(index, 1)
        this.$emit('change')
      })
    },
    handleWidgetClear(index) {
      this.localData.column[index].children.column = []
      this.selectWidget = this.localData.column[index]
      this.$emit('change')
    },
    async handleWidgetClone(index) {
      let cloneData = this.deepClone(this.localData.column[index])

      cloneData.isAllowEdit = cloneData.isAllowEdit ? 'Y' : undefined
      cloneData.uuid = generateValidUuid()
      cloneData.prop = cloneData.uuid

      this.localData.column.splice(index + 1, 0, cloneData)
      // this.data.column.push(cloneData);
      this.$nextTick(() => {
        this.handleSelectWidget(index + 1)
        this.$emit('change')
      })
    },
    // 复制组件时对整个组件进行遍历，避免添加重复的标题和属性值
    getCloneCompLabel(label) {
      let i = randomString()
      let newLabel = String(label.slice(0, 10) + i).slice(0, 20)
      return newLabel
    },
    isShowButton(column) {
      // 与子表单内部的同名组件区分
      return this.selectWidget.prop == column.prop && !this.selectWidget.parentName
    }
  }
}
</script>